define(function(require, exports, module){
	require("resource/js/easyui/themes/icon.css");
	require("resource/js/easyui/easyloader.js");
	require("resource/js/component/rules.js");
	require("dcs/section/css/questions.css");
	var AJAX = require("resource/js/component/ajax.js");
	var CONST = require("resource/js/config/const.js");
	var E = require("resource/js/component/easyutil.js");
	var EC = require("resource/js/component/easycombobox.js");
	EC.create({
		url:BASEPATH+"/base/authoriza/basecode/getType.htm",
		param:{checkeds:"status,systype,deptType,con_scheduler"}
	});
	var userModel ;
	var obj={};
	var config =function(){
		return{
			type:"dept",
			name:'标段设置',
			column:[[
				        {field:'id',title:'id',width:100,align:'center',height:50,hidden:true},
				        {field:'deptName',title:'标段名称',width:100,align:'center',height:50},
				        {field:'chargeName',title:'负责人',width:100,align:'center',height:50},
				        {field:'chargeTel',title:'电话',width:100,align:'center',height:50},
				        {field:'xxx',title:'线路逐桩表配置',width:100,align:'center',height:50,formatter:function(value,row,index){
				        	if(row.isImport == '0'){
				        		return "<span><a class='preview tab_style' index='"+index+"'>预览</a></span><span><a class='download tab_style_01' index='"+index+"'>下载</a></span>";
				        	} else {
				        		return "<span><a class='config tab_style' index='"+index+"'>配置</a></span>";
				        	}
				        	
				        }},
				        {field:'xxxx',title:'操作',width:100,align:'center',height:50,formatter:function(value,row,index){
				        	return "<span><a class='configArea tab_style' index='"+index+"'>设置工区</a></span>";
				        }},
				        
				        ]]
		};
	}
	var dgutil = undefined;
	var datagridconfig = undefined;
	function initPage(){
		//initDeptTree();
		//EC.init({ ele:"#searchState",prompt:obj.get("base.dept.js.dept.pleaseSelectTheAvailableState"), grouptype:"status", value:"0"});
		//EC.init({ ele:"#searchDeptType",prompt:obj.get("base.dept.js.dept.pleaseChooseTheNatureOfTheDepartment"), grouptype:"deptType" });
		dgutil = new E.ajaxDataGrid(datagridconfig);
		//initSelParentDept('searchDeptParentName','searchDeptParent');
	}
	
	var configFunc = function(url,row){
		impRoadInit(url,row);
	}
	var downloadFunc = function(isModel,row){
		exportExcelXml(isModel,row);
	}
	var configAreaFunc = function(baseUrl,row){
		workAreaAdd(baseUrl,row);
	}
	var previewFunc = function(url,row){
		previewInit(url,row);
	}
	
	var initSelParentDept=function(textName,valName,systype,row){
		if(systype==undefined||systype==null){
			systype = '';
		}
		var currentDept="";
		if(row){
			//console.log(row);
			$("#"+valName).val(row.deptParent);
			currentDept = row.deptId;
		}else{
			$("#"+valName).val('');
		}
		$("#"+textName).textbox({
			buttonText: '上级组织选择',
			prompt:'',
			/*icons:[{
				iconCls:'icon-clear',
				handler: function(e){
					$("#"+valName).val('');
					$("#"+textName).textbox('setValue', '');
				}
			}],*/
			onClickButton:function(){
				$("#treeselecter1").dialog("open");
				using("ztree",function(){
					/*if($('#treeselecter1').dialog('options').isLoad){
						return;
					}*/
					var T = require("resource/js/component/treeutil.js");
					var tree = new T.ajaxTree({
						eid:"treeselecter1",
						url:BASEPATH+"/base/authoriza/dept/getTreeall.htm?status=0&systype="+systype,
						check:"radio",
						title:obj.get("base.dept.js.dept.departmentSelection"),
						checks:[$("#"+valName).val()],
						disable:function(node){
							if(node.id==currentDept){
								node.nocheck=true;
							}
							return false;
						},
						autoclose:false,
						save:function(data){
							var msg = "";
							if(textName!="add_deptParentName"){
								msg = validateDeptParent();
							}
							if(msg!=""){
								$.messager.confirm(obj.get("dept.systemHints"),msg,function(r){
							    	if(r){
							    		$("#"+textName).textbox("setValue",data[0].name);
										$("#"+valName).val(data[0].id);
										$('#treeselecter1').dialog('close');
									}
								});
							}else{
								$("#"+textName).textbox("setValue",data[0].name);
								$("#"+valName).val(data[0].id);
								$('#treeselecter1').dialog('close');
							}
						}
					});
					tree.load(function(obj){
						if($("#"+valName).val()!=""){
							var node = obj.getNodeByParam("id", $("#"+valName).val(), null);
							if(node){
								$("#"+textName).textbox("setValue",node.name);
							}
						}
					});
				});
			}
		});
		if(row){
			$("#"+textName).textbox('setValue', row.deptParentName);
		}else{
			$("#"+textName).textbox('setValue', '');
		}
	}
	var initDeptTree=function(){
		require("resource/js/component/tree.js");
		using('menu',function(){
			$("#deptTree").tree({
				searchable:false,
				title:'组织架构',
				url:BASEPATH+"/base/authoriza/dept/getTreeall.htm?status=0",
				setting:{
					menu:{
						enable:true,
						items:['refresh','showchild']
					},
					callback:{
						onClick:function(event, treeId, treeNode){
							$("#searchDeptParent").val(treeNode.id);
							$("#searchDeptParentName").textbox('setValue',treeNode.name);
							dgutil.pager(1);
						}
					},
					async:{
						showRefresh:true,
						enable:true,
						autoParam:["text=type","id"],
						url:BASEPATH+"/base/authoriza/dept/getTreeall.htm?status=0",
						type:"get"
					}
				}
			});
		});
	}
	//角色分配按钮事件
	var roleDialogInit = function(baseUrl,rows){
		var deptId = rows.deptId;
		var url = BASEPATH+"/base/authoriza/role/getRoleByDept.htm";
		var ajax = AJAX.init();
		var intiRoleTree = function(code,msg,data){
			var checks = [];
			var regexp = "";
			if(data!=undefined&&data.length>0){
				for(var k=0;k<data.length;k++){
					checks[k] = data[k].roleId;
					if(data[k].regexp!=undefined&&data[k].regexp!=''){
						regexp = data[k].regexp;
					}
				}
			}
			$("#treeselecter").dialog("open");
			using("ztree",function(){
				var T = require("resource/js/component/treeutil.js");
				var tree = new T.ajaxTree({
					eid:"treeselecter",
					url:BASEPATH+"/base/authoriza/role/getTreeall.htm",
					check:"checkbox",
					title:obj.get("base.dept.js.dept.roleSelection"),
					checks:checks,
					save:function(data){
						var checks = '';
						for(var k=data.length-1;k>=0;k--){
							if(k==0) checks+=data[k].id;
							else checks+=data[k].id+",";
						}
						//var url = BASEPATH+"/base/authoriza/dept/saveDeptRole.htm";
						AJAX.init().success(function(code,msg,data){
							if(data){
								$.messager.show({ title:obj.get("base.dept.js.dept.systemHints"), msg:obj.get("base.dept.js.dept.saveSuccess"), timeout:5000, showType:'slide' });
							}
						}).error(function(code,msg,data){
							$.messager.show({ title:obj.get("base.dept.js.dept.systemHints"), msg:obj.get("base.dept.js.dept.saveFailure"), timeout:5000, showType:'slide' });
						}).post(baseUrl,{deptId:deptId,checkeds:checks});
					}
				});

				tree.setting.callback.beforeCheck=function(treeId, treeNode) {
					if(treeNode.checked)
						return true;
					else {
						var treeobj = this.getZTreeObj(treeId);
						treeobj.setting.check.chkboxType={ "Y": "ps", "N": "ps" }
						treeobj.checkNode(treeNode,false,true,false);
						treeobj.setting.check.chkboxType={ "Y": "", "N": "" }
						return true;
					}
				}
				tree.load();
			});
		}
		ajax.success(intiRoleTree).error(intiRoleTree).post(url,{deptId:deptId});
	}

	var onSelectSys=function(record){
		$("#deptParentName").ztreebox("options").onLoad = function(){
			var tree = $("#deptParentName").ztreebox("ztree");
			if($("#deptId").val()&&$("#deptId").val()!=""){
				var node = tree.getNodeByParam("id",$("#deptId").val());
				if(node){
					tree.setChkDisabled(node,true,false,true);
				}
			}
			var deptParent = $("#deptParentName").textbox('getValue');
			if(deptParent&&deptParent!=""){
				var node = tree.getNodeByParam("id",deptParent);
				if(!node){
					$("#deptParentName").textbox('setValue',record.deptParentName);
					$("#deptParentName").next().find("input[type='hidden']").val(deptParent);
				}
			}
		}
		$("#deptParentName").ztreebox("reload",BASEPATH+"/base/authoriza/dept/getTreeall.htm",{status:"0",systype:record.baseCode});
	}
	
	var addDialogInit = function(baseUrl){
		
		$("#adddlg").dialog({
			iconCls: 'icon-save',
			title:config().name+obj.get("base.dept.js.dept.add"),
			href:baseUrl,
			onLoad:function(){
				
				//$("#add_deptParentName").textbox('setValue',row.deptName);
				//$("#add_deptParent").val(row.deptId);
				//EC.init({ ele:"#deptType",grouptype:"con_scheduler"});
		    },
		    
			buttons: [{
				text:obj.get("base.dept.js.dept.save"),
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#addform").form("validate")){
							
							var obj = $("#addform").serializeJson();
							/**
							 * 处理项目Id，获取项目Id作为标段pid
							 */
							var deptParent = sessionStorage.getItem('projectId');
							if(deptParent == null || deptParent == undefined){
								deptParent = '190401142719000007';
							}
							obj.deptParent = deptParent;
							
							obj.base_name = '1';
							
							E.ajaxHandler(BASEPATH+'/base/authoriza/dept/save.htm',obj,function(){
								dgutil.pager();
								$("#adddlg").dialog("close");
							});	
						}
					});
				}
			},{
				text:obj.get("base.dept.js.dept.cancel"),
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#adddlg').dialog('close');
					$("#dd").tooltip("hide");
				}
			}]
		});
		$("#adddlg").dialog("open");
	}
	var workAreaAdd = function(baseUrl,row){
		
		$("#adddlg").dialog({
			iconCls: 'icon-save',
			title:config().name+obj.get("base.dept.js.dept.add"),
			href:baseUrl,
			onLoad:function(){
				var addtr = "<tr>"+
							"<td class='key'><span>*</span>工区名称:</td>"+
							"<td style='width:200px;'><input class='easyui-textbox' type='text' id='deptName' name='deptName' data-options=\"validType:'maxlength[15]',required:true,prompt:'请输入工区名称'\"/>" +
							"<input type='hidden' name='deptId'>"+
							"</td>"+
							"<td style='width:20px;'><span id='addttr' class='addttrStyle'></span></td>"+
							"<td><span id='removetr' class='removetrStyle'></span></td>"+
							"</tr>";
				var addtr1 = "<tr>"+
								"<td class='key'><span>*</span>工区名称:</td>"+
								"<td style='width:200px;'><input class='easyui-textbox' type='text' id='deptName' name='deptName' data-options=\"validType:'maxlength[15]',required:true,prompt:'请输入工区名称'\"/>" +
								"<input type='hidden' name='deptId'>"+
								"</td>"+
								"<td><span id='removetr' class='removetrStyle'></span></td>"+
								"</tr>";
				
				$("#deptParentId_work").val(row.sectionId);
				AJAX.init().sync().success(function(code,msg,data){
					
					if(data && data.length > 0){
						if(data.length == 2){
							$("#deptName1").textbox('setValue',data[0].workAreaName);
							$("#deptId1").val(data[0].sectionId);
							$("#deptName2").textbox('setValue',data[1].workAreaName);
							$("#deptId2").val(data[1].sectionId);
						} else if(data.length > 2){
							$('#work_table').find('tr').last().find('td').eq(2).remove();
							for(var i = 0; i < data.length-2; i ++){
								if(i == data.length-3){
									$('#work_table').append(addtr);
								} else {
									$('#work_table').append(addtr1);
								}
							}
							$.parser.parse('#work_table');
							for(var j = 0; j < data.length; j ++){
								if(j < 2){
									$('#work_table').find('tr').eq(j).find('td').eq(1).find("#deptName"+(j+1)).textbox("setValue",data[j].workAreaName);
								} else {
									$('#work_table').find('tr').eq(j).find('td').eq(1).find("#deptName").textbox("setValue",data[j].workAreaName);
								}
								$('#work_table').find('tr').eq(j).find('td').eq(1).find("input[name='deptId']").val(data[j].sectionId);
							}
						}
						
					}
				}).post(BASEPATH + '/dcs/section/queryWorkArea.htm', {
					sectionId:row.sectionId
				});
				
				var addOption = function(){
					$(".addttrStyle").bind('click',function(){
						$(this).parent().remove();
						$("#work_table").append(addtr);
						
						var lastAddTd = "<td style='width:20px;'><span id='addttr' class='addttrStyle'></span></td>";
						var lastRemoveTd_ = "<td><span></span></td>"; 
						
						var removeOption = function(){
							$(".removetrStyle").unbind('click').bind('click',function(){
								$(this).parent().parent().remove();
								var trNum2 = $('#work_table').find('tr').length;
								if(trNum2 == 2){
									$('#work_table').find('tr').last().find('td').eq(2).remove();
									$('#work_table').find('tr').last().append(lastAddTd);
									$('#work_table').find('tr').last().append(lastRemoveTd_);
								}
								addOption();
								removeOption();
							});
						}
						removeOption(); 
						addOption();
					});
					$.parser.parse('#work_table');
				}
				addOption();
				
				var removeOption_forUpd = function(){
					$(".removetrStyle").unbind('click').bind('click',function(){
						var lastAddTd = "<td style='width:20px;'><span id='addttr' class='addttrStyle'></span></td>";
						var lastRemoveTd_ = "<td><span></span></td>"; 
						$(this).parent().parent().remove();
						var trNum2 = $('#work_table').find('tr').length;
						if(trNum2 == 2){
							$('#work_table').find('tr').last().find('td').eq(2).remove();
							$('#work_table').find('tr').last().append(lastAddTd);
							$('#work_table').find('tr').last().append(lastRemoveTd_);
						}
						addOption();
						removeOption_forUpd();
					});
				}
				removeOption_forUpd();
			},
			
			buttons: [{
				text:obj.get("base.dept.js.dept.save"),
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#workform").form("validate")){
							
							var obj = $("#workform").serializeJson();
							
							var trNum2 = $('#work_table').find('tr').length;
							var ck = [];
							if(trNum2 > 0){
								for(var i = 0; i < trNum2; i ++){
									var d = $('#work_table').find('tr').eq(i).find('td').eq(1).find("input[name='deptName']").val();
									var d_ = $('#work_table').find('tr').eq(i).find('td').eq(1).find("input[name='deptId']").val();
									var o = {};
									o.deptName = d;
									o.deptId = d_;
									ck.push(o);
								}
							}
							
							obj.des = JSON.stringify(ck);
							delete obj.deptName;
							delete obj.deptId;
							
							//obj.checkeds = obj.deptName.join(',');
							obj.base_name = '2';
							
							E.ajaxHandler(BASEPATH+'/base/authoriza/dept/save.htm',obj,function(){
								dgutil.pager();
								$("#adddlg").dialog("close");
							});	
						}
					});
				}
			},{
				text:obj.get("base.dept.js.dept.cancel"),
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#adddlg').dialog('close');
					$("#dd").tooltip("hide");
				}
			}]
		});
		$("#adddlg").dialog("open");
	}

	var updDialogInit = function(baseUrl,row){
		
		$("#adddlg").dialog({
			iconCls: 'icon-save',
			title:config().name+obj.get("base.dept.js.dept.update"),
			href:baseUrl,
			onLoad:function(){
				using("form",function(){
					/*if(row.deptCode.length == 4){
						$(".for_hide").hide();
					}
					if(row.deptCode.length == 12){
						*//**
						 * 动态处理表单
						 *//*
						var str ="<tr>"+
								"<td class='key'><span></span>施工状态:</td>"+
								"<td><input class='easyui-combobox' type='text' id='deptType' name='deptType'  validType=\"\" data-options=\"prompt:''\"/></td>"+
								"</tr>";		
						$('#form_table').append(str);
						$.parser.parse('#form_table');
					}
					$("#upd_deptParentName").textbox('setValue',row.deptParentName);
					$("#upd_deptParent").val(row.deptParent);
					EC.init({ ele:"#deptType",grouptype:"con_scheduler"});*/
					
					
					
					/*$('#chargeTel').textbox('setValue',row.chargeTel);
					$('#chargeName').textbox('setValue',row.chargeName);
					$('#pile_location').textbox('setValue',row.pileLocation);
					$('#road_width').numberbox('setValue',row.roadWidth);*/
					
					row.phone = row.chargeTel;
					row.contactsperson = row.chargeName;
					row.area = row.roadWidth;
					row.deptId = row.sectionId;
					row.deptParent = row.deptParentId;
					
					$('#updform').form('load',row);
				});
				$('.tooltip[tabindex="-1"]').remove();
		    },
			buttons: [{
				text:obj.get("base.dept.js.dept.save"),
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#updform").form("validate")){
//							if($("#upd_deptParent").val()==""){
							
								var obj = $("#updform").serializeJson();
								obj.base_name = '1';//标识为标段
								E.ajaxHandler(BASEPATH+'/base/authoriza/dept/update.htm',obj,function(){
									dgutil.pager();
									$("#adddlg").dialog("close");
								});	
//							}
						}
					});
				}
			}/*,{
				text:'重置',
				accessKey:{akey:18,mkey:82},
				handler:function(){
					using("form",function(){
						$('#updform').form('load',row);
						

						EC.init({ ele:"#status",grouptype:"status",value:row.status});
						$("#deptParentName").ztreebox({});
		
						if(userModel.userType==CONST.USERTYPE.SUPERUSER){
							EC.init({ ele:"#systype",grouptype:"systype",value:row.systype,onSelect:onSelectSys});
							onSelectSys({baseCode:row.systype});
						}else{ //当前用户非超级管理员 系统类型和用户是一样
							EC.init({ ele:"#systype",grouptype:"systype",value:userModel.sysType,readonly:true});
							onSelectSys({baseCode:userModel.sysType});
							$("#systype").closest("tr").hide();
						}
					});
				}
			}*/,{
				text:obj.get("base.dept.js.dept.cancel"),
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#adddlg').dialog('close');
					$("#dd").tooltip("hide");
				}
			}]
		});
		$("#adddlg").dialog("open");
	}
	/**
	 * 校验当前用户所选上部门是否为当前部门的子级部门
	 * 如果是 则提示用户是否确定进行此操作 若确定 则将改修改为上部门的子部门的上部门改为修改为上部门的上部门
	 */
	var validateDeptParent =function(){
		var deptId = $("#deptId").val();
		var deptName = $("#deptName").val();
		var treeObj = $.fn.zTree.getZTreeObj("treeselecter1_tree");
		var nodes = treeObj.getCheckedNodes(true);
		var parent = nodes[0].getParentNode();
		if(parent=null||parent==undefined){
			return '';
		}
		var res = checktreeNodeParent(parent,deptId);
		var ppName = obj.get("base.dept.js.dept.firstLevelDepartment");
		if(res.pId!=null){
			ppName = res.getParentNode().name;
		}
		if(res!=null&&res.hasOwnProperty("id")){
			return obj.get("base.dept.js.dept.youConfirmThat")+'【'+nodes[0].name+'】'+obj.get("base.dept.js.dept.departmentChangedTo")+'【'+deptName+'】'+obj.get("base.dept.js.dept.isItTheDepartmentsUpperDepartment?IfItIsConfirmed")+'，【'+nodes[0].name+'】'+obj.get("base.dept.js.dept.theDepartmentWillBeUpgradedTo")+'【'+ppName+'】'+(res.pId!=null?obj.get("base.dept.js.dept.subDepartmentOfTheDepartment"):'');
			/*$.messager.confirm('系统提示','您确认将【'+nodes[0].name+'】部门改为【'+deptName+'】部门的上部门吗？如果确认，【'+nodes[0].name+'】部门将升级为【'+ppName+'】'+(res.pId!=null?'部门的子部门！':''),function(r){
			    	return true;
			});*/
		}else{
			return '';
		}
	}
	var checktreeNodeParent = function(parent,deptId){
		if(parent==null){
			return '';
		}
		if(parent.id==deptId){
			return parent;
		}else{
			if(parent.pId==null){
				return "";
			}
			return checktreeNodeParent(parent.getParentNode(),deptId);
		}
		
	}
	var areaInputTree = function(treeDialogId, areaNameInput, areaidInput){
		$("#" + areaNameInput).textbox({
			buttonText: obj.get("base.dept.js.dept.administrativeDivision"),
			prompt:obj.get("base.dept.js.dept.pleaseChooseTheAdministrativeDivision"),
			onClickButton:function(){
				function zTreeBeforeCheck(treeId, treeNode) {								
					if(treeNode.isparent){									
					       return false;
					}

				};
				$("#" + treeDialogId).dialog("open");
				var T = require("resource/js/component/treeutil.js");
				using("ztree",function(){
					if($('#' + treeDialogId).dialog('options').isLoad){
						return;
					}
					var tree = new T.ajaxTree({
						eid:treeDialogId,
						url:BASEPATH+"/base/authoriza/conmonData/queryData.htm?queryId=basearea",
						check:"radio",
						title:obj.get("base.dept.js.dept.administrativeDivision"),
						checks:[$("#" + areaidInput).val()],
						/*disable:function(node){
							if(node.id.length<10){
								return true;
							}
						},*/
						save:function(data){
							if(data[0].id!=''){
								$("#" + areaNameInput).textbox("setValue",data[0].name);
								$("#" + areaidInput).val(data[0].id);
							}else{
								return;
							}

						},
				        data: {
				    		simpleData: {
				    			enable: true,
				    			idKey:"id",
				    			pIdKey:"pid"
				    		}
				    	},
				    	callback:{
				    		beforeCheck: zTreeBeforeCheck
				    	}
					});
					tree.load(function(obj){
						var node = obj.getNodesByFilter(function(node){
							if(node.isparent){
								obj.setChkDisabled(node, true);
							}
						}, false);
						if($("#" + areaidInput).val()!=""){
							var node = obj.getNodeByParam("id", $("#" + areaidInput).val(), null);
							if(node){
								$("#" + areaNameInput).textbox("setValue",node.name);
							}
						}
					});
				});
			}
		});
	}
	
	var areaEditTree = function(){
		$("#editAreaName").textbox({
			buttonText: obj.get("base.dept.js.dept.administrativeDivision"),
			prompt:obj.get("base.dept.js.dept.pleaseChooseTheAdministrativeDivision"),
			onClickButton:function(){
				function zTreeBeforeCheck(treeId, treeNode) {								
					if(treeNode.isparent){									
					       return false;
					}

				};
				$("#treeselecter3").dialog("open");
				var T = require("resource/js/component/treeutil.js");
				using("ztree",function(){
					if($('#treeselecter3').dialog('options').isLoad){
						return;
					}
					var tree = new T.ajaxTree({
						eid:"treeselecter3",
						url:BASEPATH+"/base/authoriza/conmonData/queryData.htm?queryId=basearea",
						check:"radio",
						title:obj.get("base.dept.js.dept.administrativeDivision"),
						checks:[$("#areaId").val()],
						/*disable:function(node){
							if(node.id.length<10){
								return true;
							}
						},*/
						save:function(data){
							if(data[0].id!=''){
								$("#editAreaName").textbox("setValue",data[0].name);
								$("#editArea").val(data[0].id);
								/*if(data[0].getParentNode()&&data[0].getParentNode().getParentNode()){
									$.fn.mapbox.localtext=data[0].getParentNode().getParentNode().name+data[0].getParentNode().name;
								}else if(data[0].getParentNode()){
									$.fn.mapbox.localtext=data[0].getParentNode().name+data[0].name;
								}else{
									$.fn.mapbox.localtext=data[0].name;
								}*/
							}else{
								return;
							}

						},
				        data: {
				    		simpleData: {
				    			enable: true,
				    			idKey:"id",
				    			pIdKey:"pid"
				    		}
				    	},
				    	callback:{
				    		beforeCheck: zTreeBeforeCheck
				    	}
					});
					tree.load(function(obj){
						var node = obj.getNodesByFilter(function(node){
							if(node.isparent){
								obj.setChkDisabled(node, true);
							}
						}, false);
						if($("#editArea").val()!=""){
							var node = obj.getNodeByParam("id", $("#" + areaIdInput).val(), null);
							if(node){
								$("#editAreaName").textbox("setValue",node.name);
							}
						}
					});
				});
			}
		});
	}
	var serid = '';
	var impRoadInit = function(url,row){
		
		if(row.isImport == '0'){
			$.messager.show({title:'系统提示',msg:'已导入路桩，不允许重复导入',timeout:5000,showType:'slide'});
			return;
		}
		
		using(["dialog", "form", 'parser','combobox', 'messager',"filebox"], function(){
			$("#impMemberDialog").dialog({
				iconCls: 'icon-save',
				title:'路桩配置',
				href:url,
				onLoad:function(){
					$("#sectionIdInput").val(row.sectionId);
				},
				buttons:[{
					text:'下载导入模板',
					iconCls:'',
					handler:function(){
						window.location.href = BASEPATH + "/resource/impRoadPileTemplate.xls";
					}
				},
				{
					text:'导入',
					handler:function(){
						if($("input[name='file']").val() == ''){
							$.messager.alert('系统提示','请选择需要导入的excel文件');
							return;
						}
						var impResult = {};
						$("#impMemberForm").attr("action", BASEPATH+'/base/authoriza/excel/import.htm?serid='+serid);
						$('#impMemberForm').form('submit', {
						    success: function(data){
						    	impResult = JSON.parse(data);
						    	if(impResult.code == 0){
						    		
						    		jumpToValidate(BASEPATH+"/view/dcs/section/validateError",impResult.data.SERID,$("#sectionIdInput").val());
						    		
								}else if(impResult.code == 13){//impResult.data.SERID
									//打开异常数据展示将界面
									serid=impResult.data.SERID;
									$('#impMemberDialog').dialog('close');
									importErrorInfo("errorMemberDialog",serid);
									//excel.errorParkingInfo("errorMemberDialog",serid);
								}else{
						    		$.messager.alert('系统提示','导入失败'+':'+impResult.msg);
						    	}
						    }
						});
					}
				},
				{
					text:'取消',
					addClass:'l-btn-red',iconCls:'icon-not',
					handler:function(){
						$('#impMemberDialog').dialog('close');
					}
				}]
			});
			$("#impMemberDialog").dialog("open");
		});
	}
	var previewInit = function(url,row){
		
		using(["dialog", "form", 'parser','combobox', 'messager',"filebox"], function(){
			$("#previewDialog").dialog({
				iconCls: 'icon-save',
				title:'路桩预览',
				href:url,
				onLoad:function(){
					
					AJAX.init().sync().success(function(code,msg,data){
						
						var map = new BMap.Map("baiduMap");
					    var point = new BMap.Point(116.404, 39.915);
					  
					    map.addControl(new BMap.ScaleControl()); // 添加比例尺控件

					    var pointArr1 = data;

					    var pointArr=[];
					    for (var k = 0; k < pointArr1.length; k += 1) {
					        
					       pointArr.push({
					                lng: pointArr1[k].lng,
					                lat: pointArr1[k].lat,
					                pile_key:pointArr1[k].pile_key
					            });
					     
					    }

					    // 生成坐标点
					    var trackPoint = [];
					    for (var i = 0, j = pointArr.length; i < j; i++) {
					       var point =  new BMap.Point(pointArr[i].lng, pointArr[i].lat);
					       point.title = pointArr[i].pile_key;
					        trackPoint.push(point);
					    }
					    map.centerAndZoom(trackPoint[0], 15);
					    //开启滑轮滚动
					    map.enableScrollWheelZoom();

					    // 画线
					    var polyline = new BMap.Polyline(trackPoint, {
					        strokeColor: "#ad0e21",
					        strokeWeight: 1,
					        setStrokeStyle:"dashed",
					        strokeOpacity: 1
					    });
					    map.addOverlay(polyline);
					    // 配置图片
					    var size = new BMap.Size(10, 10);
					    var offset = new BMap.Size(0, -4.5);
					    var imageSize = new BMap.Size(10, 10);
					    var icon = new BMap.Icon(BASEPATH+"/dcs/section/images/ic_tomap3.png", size, {
					        imageSize: imageSize,
					        infoWindowAnchor:new BMap.Size(0, -3)
					    });


					    // 画图标
					    for (var i = 0, j = trackPoint.length; i < j; i++) {
					        var marker = new BMap.Marker(trackPoint[i], {
					            icon: icon,
					            title:trackPoint[i].title,
					            offset: offset
					        }); // 创建标注
					        map.addOverlay(marker);
					        marker.addEventListener("click",function () {
					             // alert(this.getPosition())
					            var point=this.getPosition();
					            alert("经度："+point.lng+"\n"+"纬度："+point.lat)
					        })

					    }

					    //根据经纬极值计算绽放级别。 (从网上复制)
					    function getZoom(maxLng, minLng, maxLat, minLat) {
					        var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "2000000"]; // 级别18到3。
					        var pointA = new BMap.Point(maxLng, maxLat); // 创建点坐标A
					        var pointB = new BMap.Point(minLng, minLat); // 创建点坐标B
					        var distance = map.getDistance(pointA, pointB).toFixed(1); //获取两点距离,保留小数点后两位
					        for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
					            if (zoom[i] - distance > 0) {
					                return 18 - i + 3; //之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
					            }
					        }
					    }

					    //  (从网上复制)
					    function setZoom(points) {
					        if (points.length > 0) {
					            var maxLng = points[0].lng;
					            var minLng = points[0].lng;
					            var maxLat = points[0].lat;
					            var minLat = points[0].lat;
					            var res;
					            for (var i = points.length - 1; i >= 0; i--) {
					                res = points[i];
					                if (res.lng > maxLng) maxLng = res.lng;
					                if (res.lng < minLng) minLng = res.lng;
					                if (res.lat > maxLat) maxLat = res.lat;
					                if (res.lat < minLat) minLat = res.lat;
					            }
					            var cenLng = (parseFloat(maxLng) + parseFloat(minLng)) / 2;
					            var cenLat = (parseFloat(maxLat) + parseFloat(minLat)) / 2;
					            var zoom = getZoom(maxLng, minLng, maxLat, minLat);
					            map.centerAndZoom(new BMap.Point(cenLng, cenLat), zoom);
					        } else {
					            //没有坐标，显示全中国
					            map.centerAndZoom(new BMap.Point(103.388611, 35.563611), 5);
					        }
					    }

					    setZoom(pointArr);
					}).error().post(BASEPATH+'/dcs/section/queryAllGPS.htm',{sectionId:row.sectionId});
					
				},
				buttons:[
				   {
					text:'取消',
					addClass:'l-btn-red',iconCls:'icon-not',
					handler:function(){
						$('#previewDialog').dialog('close');
					}
				}]
			});
			$("#previewDialog").dialog("open");
		});
	}
	var downFile = function(url,method,data){
		var form = $('<form method="'+method+'" action="' + url + '">');
		$.each(data, function(k, v) {
			form.append($('<input type="hidden" name="'+ k + '" value="' + v + '">'));
		});
		form.append($('</form>'));
		form.appendTo('body').submit().remove();
		return;
	}
	var exportExcelXml = function(isModel,row){
		//var down = require("resource/js/component/downExcelXml.js");
		var url = BASEPATH+'/base/genExcelXml/download.htm';
		var method = "GET";
		var param = '';
		//拼接参数
		var searchForm = $("#searchform").serializeArray();//[{name:'',value:''}]
		/*$.each(searchForm, function(index, value){
			if(index != 0){
				param += ",";
			}
			param +=value.value;
		});*/
		var data = {};
		data.queryId = "importRoadPile";
		data.param = row.sectionId;
		data.isModel=isModel;
		//down.downFile(url,method,data);
		downFile(url,method,data);
	}
	//重写导入错误展示插件
	var importErrorInfo = function(id,serid){
    	$("#"+id).dialog({
			iconCls: 'icon-save',
			title:'错误数据',
			href:BASEPATH+"/view/base/errorExport/errorExport",
			onLoad:function(){
				seajs.use("base/errorExport/js/errorExport",function(errorExport){
					errorExport.serid = serid;
					errorExport.trans();
				});
			},
			onClose:function(){
				easyutil.ajaxHandler(BASEPATH+"/dcs/section/deleteImpData.htm",{"batchId":serid},function(){
					dgutil.pager();
				});
			}
		});
		$("#"+id).dialog("open");
    }
	var jumpToValidate = function(baseUrl,batchId,sectionId){
		//$("#errorMemberDialog").dialog({})
		
		$("#validateDialog").dialog({
			iconCls:"icon-save",
			title:'导入数据校验',
			href:baseUrl,
			onLoad:function(){
				
				require.async("dcs/section/js/validateError",function(validate){
					var o_ = {};
					o_.batchId = batchId;
					o_.sectionId = sectionId; 
					validate.trans(o_);
				});
			},
			buttons:[],
			onClose:function(){
				E.ajaxHandler(BASEPATH+"/dcs/section/deleteImpData.htm",{"batchId":batchId},function(){
					dgutil.pager();
				});
			}
		});
		$("#impMemberDialog").dialog("close");
		
		$("#validateDialog").dialog("open");
	}
	
	var checkIsImport = function(rows){
		var flag = false;
		for(var i = 0; i < rows.length; i ++){
			if(rows[i].isImport == '0'){
				flag = true;
				break;
			}
		}
		return flag;
	}
	var delInit = function(baseUrl,rows){
		if(checkIsImport(rows)){
			$.messager.show({title:'系统提示',msg:'已导入路桩，不允许删除',timeout:5000,showType:'slide'});
			return;
		}
		var checks = "";
		for(var key in rows){
			if(key==rows.length-1){
				checks += rows[key].sectionId;
			}else{
				checks += rows[key].sectionId+",";
			}
		}
		AJAX.init().success(function(){
			dgutil.delRow(rows);
		}).post(baseUrl,{checkeds:checks});
	}
	module.exports = {
		trans:function(id){
				var param=function(obj_){
					obj=obj_;
				var buttons ={ 
						title:{
							_class:"",
							text:'标段设置'
						},
						btn:[
					 {
						iconCls: 'icon-search',
						url:'/dcs/section/querySectionByPage.htm',
						text:obj.get("base.dept.js.dept.query"),
						addClass:'l-btn-display',
						handler:function(){dgutil.pager(1);}
					},{
						iconCls: 'icon-add',
						addClass:'l-btn-display',
						text:obj.get("base.dept.js.dept.add"),
						url:'/view/dcs/section/add',
						handler: addDialogInit
						//needRow:true
					},
					 {
						iconCls: 'icon-edit',
						url:'/view/dcs/section/upd',
						text:obj.get("base.dept.js.dept.update"),
						addClass:'l-btn-display',
						needRow:true,
						handler: updDialogInit
					},
					 {
						iconCls: 'icon-remove',
						url:'/base/authoriza/dept/delete.htm',
						text:'删除',
						addClass:'l-btn-display',
						needRows:true,
						isCheck:true,
						handler: delInit
					}//,
					/*{
						iconCls: 'icon-category',
						url:'/view/dcs/section/workarea',
						text:'工区设置',
						addClass:'l-btn-display',
						needRow:true,
						handler: workAreaAdd
					},*/
					/*{
						iconCls: 'icon-assign',
						url:'/base/authoriza/dept/saveDeptRole.htm',
						text:obj.get("base.dept.js.dept.roleAssignment"),
						needRow:true,
						addClass:'l-btn-display',
						handler: roleDialogInit
					},*/
					/*{
						iconCls: 'icon_55',
						text:'配置',
						url:'/view/dcs/section/impRoad',
						needRow:true,
						handler:configFunc
					 },*/
					 /*{
						iconCls: 'icon_56',
						text:'下载',
						needRow:true,
						handler: exportExcelXml
					 }*/
					]};
					datagridconfig = {
							fitColumns:true,
							singleSelect:false,
							striped:true,
							autoRowHeight:false,
							fit: true,
							toolbar:buttons,
							columns:config().column,
							eid:"dg",
							autoLoad:true,
							url:BASEPATH+'/dcs/section/querySectionByPage.htm',
							args:"searchform",
							onLoad:function(){},
							onLoadSuccess:function(data){
								$(".config").bind('click',function(){
									var index = parseInt($(this).attr('index'));
									configFunc(BASEPATH+'/view/dcs/section/impRoad',data.rows[index]);
								});
								$(".download").bind('click',function(){
									var index = parseInt($(this).attr('index'));
									downloadFunc(BASEPATH,data.rows[index]);
								});
								$(".configArea").bind('click',function(){
									var index = parseInt($(this).attr('index'));
									configAreaFunc(BASEPATH+'/view/dcs/section/workarea',data.rows[index]);
								});
								$(".preview").bind('click',function(){
									var index = parseInt($(this).attr('index'));
									previewFunc(BASEPATH+'/view/dcs/section/preview',data.rows[index]);
								});
								
							}
								
							
					};
					using(["datagrid","ztreebox","parser","textbox","messager","dialog","combobox","numberbox"],function(){
						initPage();
						/*$("#mycontainer").layout();*/
						indexApp.exec("user",function(user){
							userModel = user;
							//为用户增加系统类型
							var sysTypes = [];
							$.each(userModel.depts,function(i,item){
								sysTypes.push(item.systype);
							});
							userModel.sysTypes = sysTypes;
						});
					});
			}		
			loadI18n('base/dept',param);
		}
	
	}
});
